import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;

import org.eclipse.jdt.internal.compiler.ast.ArrayAllocationExpression;

import utils.AddToXml;
import utils.Constant;
import utils.EditToXml;
import utils.LoadXml;
import utils.SearchUtils;
import utils.Validation;
import models.*;

/**
 * Servlet implementation class ServletController
 */
@WebServlet("/ServletController")
public class ServletController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ServletController() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// Get parameter
		String identifyAction = request.getParameter("identify");

		String id = request.getParameter("id");
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		String address = request.getParameter("address");
		String age = request.getParameter("age");
		String dob = request.getParameter("dob");
		String note = request.getParameter("note");

		String searchInput = request.getParameter("searchInput");
		String searchType = request.getParameter("searchType");

		String idEdit = request.getParameter("idEdit");
		String idDelete = request.getParameter("idDelete");
		// load list student from xml
		LoadXml loadXml = new LoadXml(Constant.PATH_TO_FILE);
		List<Student> listStudent = new ArrayList<>();
		listStudent = loadXml.getStudents().getListStudent();
		/* LIST ADD EDIT DELETE VIEW */
		// If Click list
		if (identifyAction.equals("listView")) {
			request.setAttribute("listStudent", listStudent);
			RequestDispatcher view = request.getRequestDispatcher("list.jsp");
			view.forward(request, response);
		}
		// IF click add
		if (identifyAction.equals("addView")) {
			RequestDispatcher view = request.getRequestDispatcher("add.jsp");
			view.forward(request, response);
		}
		// If Click Edit Delete
		if (identifyAction.equals("euView")) {
			request.setAttribute("listStudent", listStudent);
			RequestDispatcher view = request
					.getRequestDispatcher("EditDelete.jsp");
			view.forward(request, response);
		}
		/* LIST ADD EDIT DELETE accomplish */
		// add student to xml
		if (identifyAction.equals("addStudent")) {
			List<String> listError = new ArrayList<>();
			listError = new Validation().checkErrorAdd(id, firstName, lastName,
					address, age, dob, note, "add");
			request.setAttribute("listError", listError);
			request.setAttribute("id", id);
			request.setAttribute("firstName", firstName);
			request.setAttribute("lastName", lastName);
			request.setAttribute("address", address);
			request.setAttribute("age", age);
			request.setAttribute("dob", dob);
			request.setAttribute("note", note);

			StringBuilder builder = new StringBuilder();
			for (String string : listError) {
				builder.append(string);
			}
			if (builder.toString() == null || builder.toString().equals("")) {
				Student student = new Student();
				student.setId(Integer.parseInt(id));
				student.setFirstName(firstName);
				student.setLastName(lastName);
				student.setAddress(address);
				student.setAge(Integer.parseInt(age));
				student.setDob(dob);
				student.setNote(note);
				AddToXml addToXml = new AddToXml();
				try {
					addToXml.addStudentToXml(Constant.PATH_TO_FILE, student);
				} catch (JAXBException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				request.setAttribute("listStudent", new LoadXml(
						Constant.PATH_TO_FILE).getStudents().getListStudent());
				RequestDispatcher view = request
						.getRequestDispatcher("list.jsp");
				view.forward(request, response);
			} else {
				RequestDispatcher view = request
						.getRequestDispatcher("add.jsp");
				view.forward(request, response);
			}
		}
		// search student in list
		if (identifyAction.equals("searchStudent")) {
			List<Student> resultToForm = new SearchUtils().searchInList(
					searchType, (ArrayList<Student>) new LoadXml(
							Constant.PATH_TO_FILE).getStudents()
							.getListStudent(), searchInput);
			request.setAttribute("searchInput", searchInput);
			request.setAttribute("searchType", searchType);
			request.setAttribute("listStudent", resultToForm);
			RequestDispatcher view = request.getRequestDispatcher("list.jsp");
			view.forward(request, response);
		}
		// search student in edit delete
		if (identifyAction.equals("searchStudentED")) {
			List<Student> resultToForm = new SearchUtils().searchInList(
					searchType, (ArrayList<Student>) new LoadXml(
							Constant.PATH_TO_FILE).getStudents()
							.getListStudent(), searchInput);
			request.setAttribute("searchInput", searchInput);
			request.setAttribute("searchType", searchType);
			request.setAttribute("listStudent", resultToForm);
			RequestDispatcher view = request
					.getRequestDispatcher("EditDelete.jsp");
			view.forward(request, response);
		}
		// Delete student
		if (identifyAction.equals("deleteStudent")) {
			EditToXml editToXml = new EditToXml();
			editToXml.deleteStudentToXml(Constant.PATH_TO_FILE,
					Integer.parseInt(idDelete));
			List<Student> resultToForm = new LoadXml(Constant.PATH_TO_FILE)
					.getStudents().getListStudent();
			request.setAttribute("listStudent", resultToForm);
			RequestDispatcher view = request
					.getRequestDispatcher("EditDelete.jsp");
			view.forward(request, response);
		}
		// edit student View
		if (identifyAction.equals("editStudentView")) {
			List<String> listError = new ArrayList<>();
			LoadXml loadXmlEdit = new LoadXml(Constant.PATH_TO_FILE);
			Student studentGetted = loadXmlEdit.getStudentById(Integer
					.parseInt(idEdit));

			request.setAttribute("listError", listError);
			request.setAttribute("id", studentGetted.getId());
			request.setAttribute("firstName", studentGetted.getFirstName());
			request.setAttribute("lastName", studentGetted.getLastName());
			request.setAttribute("address", studentGetted.getAddress());
			request.setAttribute("age", studentGetted.getAge());
			request.setAttribute("dob", studentGetted.getDob());
			request.setAttribute("note", studentGetted.getNote());

			RequestDispatcher view = request.getRequestDispatcher("edit.jsp");
			view.forward(request, response);
		}
		// edit student accomplish
		if (identifyAction.equals("editStudent")) {
			List<String> listError = new ArrayList<>();
			listError = new Validation().checkErrorAdd(id, firstName, lastName,
					address, age, dob, note, "");
			request.setAttribute("listError", listError);
			request.setAttribute("id", id);
			request.setAttribute("firstName", firstName);
			request.setAttribute("lastName", lastName);
			request.setAttribute("address", address);
			request.setAttribute("age", age);
			request.setAttribute("dob", dob);
			request.setAttribute("note", note);

			StringBuilder builder = new StringBuilder();
			for (String string : listError) {
				builder.append(string);
			}
			if (builder.toString() == null || builder.toString().equals("")) {
				Student student = new Student();
				student.setId(Integer.parseInt(id));
				student.setFirstName(firstName);
				student.setLastName(lastName);
				student.setAddress(address);
				student.setAge(Integer.parseInt(age));
				student.setDob(dob);
				student.setNote(note);
				
				EditToXml editToXml = new EditToXml();
				editToXml.editStudentToXml(Constant.PATH_TO_FILE, student);

				request.setAttribute("listStudent", new LoadXml(
						Constant.PATH_TO_FILE).getStudents().getListStudent());
				RequestDispatcher view = request
						.getRequestDispatcher("EditDelete.jsp");
				view.forward(request, response);
			} else {
				RequestDispatcher view = request
						.getRequestDispatcher("edit.jsp");
				view.forward(request, response);
			}
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);

	}
}
